package edu.hawaii.halealohacli.command;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.resource.sensordata.jaxb.SensorData;
import org.wattdepot.resource.source.jaxb.Source;

/**
 * Gets the Current Power of the source.
 *
 * @author Group BackR
 *
 */
public class CurrentPower implements Command {

  private String command = "current-power";
  private String arguments = "[tower | lounge]";
  private int numParams = 1;
  private String help = "Returns the current power in kW for the associated tower or lounge.";

  @Override
  public String run(String[] input, WattDepotClient client) {
    String output = "\"" + input[1] + "\" is not a valid source.";
    List<Source> sources;
    try {
      sources = client.getSources();
      for (Source source : sources) {
        // check if the tower/lounge exists in the Client's sources and
        // get the power.
        if (source.getName().equals(input[1])) {
          // Get the latest data from source.
          SensorData data = client.getLatestSensorData(source.getName());
          // Create a time stamp of the data.
          XMLGregorianCalendar timestamp = data.getTimestamp();
          // Get the power data of this time stamp.
          double currentPower = client.getPowerConsumed(source.getName(), timestamp);
          currentPower = currentPower / 1000;
          SimpleDateFormat checkTime = new SimpleDateFormat("dd-MMM-yyyy 'at' HH:mm:ss", Locale.US);
          GregorianCalendar today = new GregorianCalendar();
          // Create decimal format for the energy data by including one decimal place.
          DecimalFormat dFormat = new DecimalFormat("####.0");
          output =
              input[1] + "'s power as of " + checkTime.format(today.getTime()) + " was "
                  + dFormat.format(currentPower) + " kW";
        }
      }
    }
    catch (NotAuthorizedException e) {
      return "Unauthorized to access the sever. Try again.";
    }
    catch (BadXmlException e) {
      return "Format error";
    }
    catch (MiscClientException e) {
      return "Unexpected error. Try again.";
    }
    catch (ResourceNotFoundException e) {
      return input[1] + " does not exist!";
    }
    return output;
  }

  @Override
  public String getCommand() {
    return command;
  }

  @Override
  public int getNumParams() {
    return numParams;
  }

  @Override
  public String getHelp() {
    return command + " " + arguments + "\n" + help;
  }

}

